package com.evaluation.kexingcp.psycho.evaluation.sys.controller;

import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.evaluation.kexingcp.admin.api.entity.SysRole;
import com.evaluation.kexingcp.admin.api.entity.SysTenant;
import com.evaluation.kexingcp.admin.service.SysRoleService;
import com.evaluation.kexingcp.admin.service.SysTenantService;
import com.evaluation.kexingcp.common.core.util.R;
import com.evaluation.kexingcp.common.excel.annotation.ResponseExcel;
import com.evaluation.kexingcp.common.log.annotation.SysLog;
import com.evaluation.kexingcp.common.security.service.KexingcpUser;
import com.evaluation.kexingcp.common.security.util.SecurityUtils;
import com.evaluation.kexingcp.pay.entity.PayGoodsOrder;
import com.evaluation.kexingcp.pay.service.PayGoodsOrderService;
import com.evaluation.kexingcp.psycho.evaluation.sys.entity.CompanyAppEntity;
import com.evaluation.kexingcp.psycho.evaluation.sys.entity.EvaluationSalesmanEntity;
import com.evaluation.kexingcp.psycho.evaluation.sys.service.CompanyAppService;
import com.evaluation.kexingcp.psycho.evaluation.sys.service.EvaluationSalesmanService;
import org.springframework.security.access.prepost.PreAuthorize;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import org.springdoc.core.annotations.ParameterObject;
import org.springframework.http.HttpHeaders;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Operation;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Objects;

/**
 * 测评业务员表
 *
 * @author kexingcp
 * @date 2024-11-06 09:17:30
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/evaluationSalesman" )
@Tag(description = "evaluationSalesman" , name = "测评业务员表管理" )
@SecurityRequirement(name = HttpHeaders.AUTHORIZATION)
public class EvaluationSalesmanController {

    private final EvaluationSalesmanService evaluationSalesmanService;
    private final SysRoleService sysRoleService;
    private final SysTenantService sysTenantService;
    private final CompanyAppService companyAppService;
    private final PayGoodsOrderService payGoodsOrderService;

    /**
     * 分页查询
     * @param page 分页对象
     * @param evaluationSalesman 测评业务员表
     * @return
     */
    @Operation(summary = "分页查询" , description = "分页查询" )
    @GetMapping("/page" )
    @PreAuthorize("@pms.hasPermission('admin_evaluationSalesman_view')" )
    public R getEvaluationSalesmanPage(@ParameterObject Page page, @ParameterObject EvaluationSalesmanEntity evaluationSalesman) {
        LambdaQueryWrapper<EvaluationSalesmanEntity> wrapper = Wrappers.lambdaQuery();
        KexingcpUser user = SecurityUtils.getUser();
        List<String> roles = sysRoleService.findRolesByUserId(SecurityUtils.getUser().getId()).stream().map(SysRole::getRoleCode).toList();
        if (roles.contains("XS_USER")) {
            // 找到自己的推广码
            wrapper.eq(EvaluationSalesmanEntity::getSalesmanName, user.getName());
        }
        return R.ok(evaluationSalesmanService.page(page, wrapper));
    }


    @Operation(summary = "分页查询", description = "分页查询")
    @GetMapping("/buy")
    public R getpayGoodsOrderPage(Page page, @RequestParam(value = "salesmanName", required = false) String salesmanName) {
        LambdaQueryWrapper<PayGoodsOrder> wrapper = Wrappers.lambdaQuery();
        wrapper.eq( PayGoodsOrder::getStatus, "2" ); // 支付完成
        wrapper.eq( PayGoodsOrder::getGoodsId, "1" );  // 支付年会员
        KexingcpUser user = SecurityUtils.getUser();
        List<String> roles = sysRoleService.findRolesByUserId(SecurityUtils.getUser().getId()).stream().map(SysRole::getRoleCode).toList();

        IPage<PayGoodsOrder> list;
        if (roles.contains("XS_USER")) {
            list = setQuery(page, wrapper, user.getName());
        } else {
            if (StrUtil.isNotEmpty(salesmanName)) {
                list = setQuery(page, wrapper, salesmanName.trim());
            } else {
                list = payGoodsOrderService.page(page, wrapper);
            }
        }

        list.convert(payGoodsOrder -> {
            SysTenant sysTenant = sysTenantService.getById(payGoodsOrder.getTenantId());
            if (sysTenant != null) {
                payGoodsOrder.setTenant(sysTenant);
                CompanyAppEntity entity = companyAppService.getOne(Wrappers.lambdaQuery(CompanyAppEntity.class).eq(CompanyAppEntity::getCompanyName, sysTenant.getName()), false);
                if (entity != null) {
                    payGoodsOrder.setSalesmanName(entity.getSalesmanName());
                }
            }

            return payGoodsOrder;
        });

        return R.ok(list);
    }

    private IPage<PayGoodsOrder> setQuery(Page page, LambdaQueryWrapper<PayGoodsOrder> wrapper, String name) {
        // 找到自己的推广码
        EvaluationSalesmanEntity salesmanEntity = evaluationSalesmanService.getOne(Wrappers.lambdaQuery(EvaluationSalesmanEntity.class).eq(EvaluationSalesmanEntity::getSalesmanName, name), false);
        if (salesmanEntity != null) {
            // 找到推广码对应的租户名称
            List<CompanyAppEntity> companyAppEntities =  companyAppService.list(Wrappers.lambdaQuery(CompanyAppEntity.class).eq(CompanyAppEntity::getSalesmanCode, salesmanEntity.getSalesmanCode()));
            if (!companyAppEntities.isEmpty()) {
                List<SysTenant>  tenants = sysTenantService.list(Wrappers.lambdaQuery(SysTenant.class).in(SysTenant::getName, companyAppEntities.stream().map(CompanyAppEntity::getCompanyName).toList()));
                if (!tenants.isEmpty()) {
                    wrapper.in(PayGoodsOrder::getTenantId, tenants.stream().map(SysTenant::getId).toList());

                    return payGoodsOrderService.page(page, wrapper);
                }
            }
        }

        return Page.of(0, 0, 0);
    }

    /**
     * 通过id查询测评业务员表
     * @param id id
     * @return R
     */
    @Operation(summary = "通过id查询" , description = "通过id查询" )
    @GetMapping("/{id}" )
    @PreAuthorize("@pms.hasPermission('admin_evaluationSalesman_view')" )
    public R getById(@PathVariable("id" ) Long id) {
        return R.ok(evaluationSalesmanService.getById(id));
    }

    /**
     * 新增测评业务员表
     * @return R
     */
    @Operation(summary = "新增测评业务员表" , description = "新增测评业务员表" )
    @SysLog("新增测评业务员表" )
    @PostMapping
    @PreAuthorize("@pms.hasPermission('admin_evaluationSalesman_add')" )
    public R save() {
        KexingcpUser user = SecurityUtils.getUser();
        EvaluationSalesmanEntity evaluationSalesman = new EvaluationSalesmanEntity();

        EvaluationSalesmanEntity entity = evaluationSalesmanService.getOne(Wrappers.lambdaQuery(EvaluationSalesmanEntity.class).eq(EvaluationSalesmanEntity::getSalesmanName, user.getId()), false);
        if (entity != null) {
            return R.failed( "邀请码已存在");
        }

        evaluationSalesman.setSalesmanName(user.getName());
        evaluationSalesman.setSalesmanCode(RandomUtil.randomString(8).toUpperCase());

        return R.ok(evaluationSalesmanService.save(evaluationSalesman));
    }

    /**
     * 修改测评业务员表
     * @param evaluationSalesman 测评业务员表
     * @return R
     */
    @Operation(summary = "修改测评业务员表" , description = "修改测评业务员表" )
    @SysLog("修改测评业务员表" )
    @PutMapping
    @PreAuthorize("@pms.hasPermission('admin_evaluationSalesman_edit')" )
    public R updateById(@RequestBody EvaluationSalesmanEntity evaluationSalesman) {
        return R.ok(evaluationSalesmanService.updateById(evaluationSalesman));
    }

    /**
     * 通过id删除测评业务员表
     * @param ids id列表
     * @return R
     */
    @Operation(summary = "通过id删除测评业务员表" , description = "通过id删除测评业务员表" )
    @SysLog("通过id删除测评业务员表" )
    @DeleteMapping
    @PreAuthorize("@pms.hasPermission('admin_evaluationSalesman_del')" )
    public R removeById(@RequestBody Long[] ids) {
        return R.ok(evaluationSalesmanService.removeBatchByIds(CollUtil.toList(ids)));
    }


    /**
     * 导出excel 表格
     * @param evaluationSalesman 查询条件
   	 * @param ids 导出指定ID
     * @return excel 文件流
     */
    @ResponseExcel
    @GetMapping("/export")
    @PreAuthorize("@pms.hasPermission('admin_evaluationSalesman_export')" )
    public List<EvaluationSalesmanEntity> export(EvaluationSalesmanEntity evaluationSalesman,Long[] ids) {
        return evaluationSalesmanService.list(Wrappers.lambdaQuery(evaluationSalesman).in(ArrayUtil.isNotEmpty(ids), EvaluationSalesmanEntity::getId, ids));
    }
}